package cs236369.hw5.db;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil
{
	private static String CONFIG = "hibernate.cfg.xml";

    private static SessionFactory sessionFactory = null;

    @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory()
    {
    	Logger l = Logger.getLogger(HibernateUtil.class);
    	l.info("configuring hibernate....");
        try
        {
            // Create the SessionFactory from hibernate.cfg.xml
        	SessionFactory res = new Configuration().configure(CONFIG).buildSessionFactory();
        	l.info ("[OK] configuration is done.");
            return res;
        }
        catch (final Throwable ex)
        {
            l.fatal("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory()
    {
    	if (null == sessionFactory)
    	{
    		sessionFactory  = buildSessionFactory();
    	}
        return sessionFactory;
    }

    public static void shutdown()
    {
        // Close caches and connection pools
    	Logger.getLogger(HibernateUtil.class).info("closing session factory");
        sessionFactory.close();
        sessionFactory = null;
        Logger.getLogger(HibernateUtil.class).info("[OK] session factory closed");
    }

}
